<template>
  <a-modal :title="title" :visible="visible" @ok="handleOk" :confirmLoading="confirmLoading" @cancel="handleCancel">
    <a-form-model ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item label="用户名" prop="name">
        <a-input v-model="form.name" />
      </a-form-model-item>
      <a-form-model-item label="昵称" prop="nickname">
        <a-input v-model="form.nickname" />
      </a-form-model-item>

      <a-form-model-item label="头像" prop="avatarUrl">
        <a-upload name="file" list-type="picture-card" :show-upload-list="false" :action="baseURL + '/oauth/upload/avatar'" :before-upload="beforeUpload" @change="handleChange">
          <img v-if="form.avatarUrl" :src="form.avatarUrl" alt="avatar" />
          <div v-else>
            <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-model-item>

      <a-form-model-item label="角色" prop="roles">
        <a-select mode="multiple" style="width: 100%" v-model="form.roleIds">
          <a-select-option v-for="role in roles" :key="role.id">{{ role.name }}</a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>
<script>
import { getRoles, add, edit } from '@/api/user'
import { getBase64 } from '@/utils'

const defaultForm = {
  id: null,
  name: '',
  nickname: '',
  avatarUrl: '',
  password: '123456',
  roleIds: []
}

export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      uploadLoading: false,
      baseURL: process.env.VUE_APP_API_BASE_URL || process.env.baseURL,
      // title: '',
      visible: false,
      confirmLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },

      roles: [],
      form: { ...defaultForm },
      rules: {
        name: [
          { required: true, message: 'Please input name', trigger: 'blur' },
          { min: 2, max: 32, message: 'Length should be 3 to 5', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title: function () {
      return this.isAdd ? '新建' : '修改'
    }
  },
  methods: {
    handleCancel(e) {
      this.resetForm()
    },
    handleOk() {
      this.$refs['form'].validate(this.validate)
    },
    async validate(valid) {
      if (valid) {
        this.confirmLoading = true
        if (this.isAdd) {
          this.doAdd()
        } else {
          this.doEdit()
        }
      }
    },
    async doAdd() {
      try {
        const res = await add(this.form)
        this.$message.success({ content: '添加成功!', duration: 2 })
        this.resetForm()
        this.$emit('refreshTable')
      } catch (err) {
        this.confirmLoading = false
        console.error(err.message)
      }
    },
    async doEdit() {
      try {
        const res = await edit(this.form)
        this.$message.success({ content: '修改成功!', duration: 2 })
        this.resetForm()
        this.$emit('refreshTable')
      } catch (err) {
        this.confirmLoading = false
        console.error(err.message)
      }
    },
    resetForm() {
      this.uploadLoading = false
      this.visible = false
      this.confirmLoading = false
      this.$refs['form'].resetFields()
      this.form = { ...defaultForm }
    },
    async getRoleSelect() {
      let res = await getRoles()
      this.roles = res.data
    },
    // upload customRequest
    // async customRequest({ action, file, onSuccess, onError, onProgress }) {
    //   debugger
    //   const formData = new FormData()
    //   formData.append('file', file)
    //   try {
    //     let res = await this.$POST({
    //       url: '/basic-service/api/importFromJSON',
    //       data: formData
    //     })
    //     this.$message.success(`导入成功`)
    //   } catch (error) {
    //     this.$message.error(error)
    //   }
    // }
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        if (info.file.response.code !== 200) {
          this.$message.error(info.file.response.message)
          return
        }
        this.form.avatarUrl = info.file.response.data
        this.uploadLoading = false
        // Get this url from response in real world.
        // getBase64(info.file.originFileObj, (imageUrl) => {
        //   this.form.avatarUrl = imageUrl
        //   this.uploadLoading = false
        // })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    }
  }
}
</script>
